package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sys_menu")
@Slf4j
public class MenuController {
    @Autowired
    private MenuService menuService;

    //菜单修改
    @PostMapping("/update")
    public ResultData update(@RequestBody Menu menu) {
        menuService.updateById(menu);
        return ResultData.ok("修改成功", menu);
    }

    //菜单删除
    @GetMapping("/del")
    public ResultData del(Integer id) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, id);
        int count = menuService.count(queryWrapper);
        if (count != 0) {
            throw new BusinessException("当前菜单存在子菜单,无法删除");
        }

        menuService.removeById(id);
        return ResultData.ok("删除成功",id);
    }

    //所有菜单
    @GetMapping("/allData")
    public ResultData allData() {
        List<MenuDto> menuDtoList = menuService.allData();
        return ResultData.ok("查询成功",menuDtoList);
    }

    //菜单添加
    @PostMapping("/add")
    public ResultData add(@RequestBody Menu menu) {
        menu.setCreate_date(LocalDateTime.now());
        menuService.save(menu);
        return ResultData.ok("添加成功", menu);
    }

    //菜单详情
    @GetMapping("/rowInfo")
    public ResultData rowInfo(Integer id) {
        Menu menu = menuService.getById(id);
        return ResultData.ok("查询成功",menu);
    }
}
